/**
 * Created By zhangQ 2018/5/1
 * [数据库生成工具转换]
 */
import DbServer from '@/components/common/dbServer'
import mysqlDBHelpler from '@/components/common/mysqlDBHelper'
import store from '@/store/index'
import fs from 'fs'
import templateUtil from '@/components/templateEjs'

const fsHelper = require('@/components/common/fsHelper')

let mysqlColumn = {
  name: 'COLUMN_NAME',
  type: 'DATA_TYPE',
  remark: 'COLUMN_COMMENT',
  primaryKey: 'COLUMN_KEY'
}

/**
 * TODO(查询tab对象)
 * @auther zhangQ
 * @date 2018/5/28 17:19
 */
export function queryTbaleObj (tableName) {
  let config = store.state.generation.dataSource
  let sql = 'select * from INFORMATION_SCHEMA.Columns where  table_schema=\'' + config.database + '\' and table_name=\'' + tableName + '\''
  return new Promise((resolve, reject) => {
    mysqlDBHelpler.executeQuery(sql, config)
      .then(({ res }) => {
        let results = res
        let javaObj = {
          tableName: tableName,
          columns: [],
          oraginColumns: results,
          primaryKeys: []
        }
        results.forEach((item) => {
          let obj = columsToJavaBean(item)
          if (obj.primaryKey) {
            javaObj.primaryKeys.push(obj)
          }
          javaObj.columns.push(obj)
        })
        resolve(javaObj)
      })
  })
}

/**
 * TODO(获得列对象)
 *
 * @auther zhangQ
 * @date 2018/5/1 13:48
 */
export function getColumns (config, tableName) {
  let sql = 'select * from INFORMATION_SCHEMA.Columns where  table_schema=\'' + config.database + '\' and table_name=\'' + tableName + '\''
  return new Promise((resolve, reject) => {
    let mysqlDB = new DbServer()
    mysqlDB.addConn(config)
      .then((conn) => {
        conn.query(sql, function (error, results, fields) {
          if (error) {
            console.error(error)
            reject(new Error(error))
            return
          }
          let javaObj = {
            tableName: tableName,
            columns: [],
            oraginColumns: results,
            primaryKeys: []
          }
          results.forEach((item) => {
            let obj = columsToJavaBean(item)
            if (obj.primaryKey) {
              javaObj.primaryKeys.push(obj)
            }
            javaObj.columns.push(obj)
          })
          resolve(javaObj)
        })
      })
  })
}

/**
 * TODO(转换为javabean)
 * @auther zhangQ
 * @date 2018/5/1 21:45
 */
export function columsToJavaBean (rowObj) {
  let resType = ''
  switch (rowObj[mysqlColumn.type]) {
    case 'varchar':
      resType = 'String'
      break
    case 'int':
      resType = 'Integer'
      break
    case 'datetime':
      resType = 'Date'
      break
    case 'decimal':
      resType = 'Double'
      break
    case 'float':
      resType = 'Float'
      break
    case 'bigint':
      resType = 'Long'
      break
  }
  console.log('rowObj', rowObj)
  return {
    name: rowObj[mysqlColumn.name],
    type: resType,
    remark: rowObj[mysqlColumn.remark],
    primaryKey: rowObj[mysqlColumn.primaryKey] === 'PRI'
  }
}

/**
 * TODO(写入文件)
 * @auther zhangQ
 * @date 2018/5/4 18:53
 */
export function initTemplates (templateConfig, datas, templatePath) {
  return new Promise((resolve, reject) => {
    console.log('datas', datas)
    templateUtil.initTemplate(templateConfig.name, datas, templatePath)
      .then((res) => {
        console.log('initTemplates', res)
        return fileWrite(templateConfig.path, templateConfig.fileName, res)
      })
      .then((res) => {
        resolve(res)
      })
      .catch((res) => {
        reject(res)
      })
  })
}

/**
 * TODO(写入文件)
 * @auther zhangQ
 * @date 2018/5/4 18:53
 */
export function fileWrite (path, fileName, data) {
  return new Promise((resolve, reject) => {
    if (fsHelper.pathExists(path)) {
      fs.writeFile(path + fileName, data, { flag: 'w+' }, (err) => {
        if (err) {
          reject(new Error(err))
        } else {
          resolve('写入成功')
        }
      })
    } else {
      fsHelper.mkdirs(path).then(res => {
        fs.writeFile(path + fileName, data, { flag: 'w+' }, (err) => {
          if (err) {
            reject(new Error(err))
          } else {
            resolve('写入成功')
          }
        })
      })
    }
  })
}
